"use client"

import { useState } from "react"
import { EditOutlined, DeleteOutlined, CopyOutlined, ExclamationCircleOutlined } from "@ant-design/icons"
import { Modal, message, Card, Typography, Space, Tag, Button, Tooltip } from "antd"
import type { HostsBlock } from "../types"
import HostsBlockForm from "./HostsBlockForm"
import { useHosts } from "../contexts/HostsContext"

const { confirm } = Modal
const { Text } = Typography

interface HostsBlockCardProps {
  hostsBlock: HostsBlock
  onDelete: () => void
}

const HostsBlockCard = ({ hostsBlock, onDelete }: HostsBlockCardProps) => {
  const { updateHostsBlock } = useHosts()
  const [isEditModalVisible, setIsEditModalVisible] = useState(false)
  const [isContentExpanded, setIsContentExpanded] = useState(false)

  const handleCopy = () => {
    navigator.clipboard.writeText(hostsBlock.content)
    message.success("已复制到剪贴板")
  }

  const handleDelete = () => {
    confirm({
      title: "确定要删除此 Hosts 配置吗?",
      icon: <ExclamationCircleOutlined />,
      content: "此操作不可恢复。",
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        onDelete()
      },
    })
  }

  const handleEdit = () => {
    setIsEditModalVisible(true)
  }

  const handleUpdate = (values: any) => {
    updateHostsBlock(hostsBlock.id, {
      name: values.name,
      content: values.content,
      description: values.description,
      environment: values.environment,
    })
    setIsEditModalVisible(false)
  }

  // Format the content to highlight comments
  const formattedContent = hostsBlock.content.split("\n").map((line, index) => {
    const trimmedLine = line.trim()
    if (trimmedLine.startsWith("#")) {
      return (
        <div key={index} className="comment-line">
          {line}
        </div>
      )
    }
    return (
      <div key={index} className="active-line">
        {line}
      </div>
    )
  })

  // Generate a consistent color based on hostsBlock name
  const getBlockColor = () => {
    const hash = hostsBlock.name.split("").reduce((acc, char) => acc + char.charCodeAt(0), 0)
    const hue = hash % 360
    return `hsl(${hue}, 70%, 65%)`
  }

  // Get first letter of hostsBlock name
  const getBlockInitial = () => {
    return hostsBlock.name.charAt(0).toUpperCase()
  }

  // Count lines
  const totalLines = hostsBlock.content.split("\n").length
  const displayLines = isContentExpanded ? formattedContent : formattedContent.slice(0, 8)

  return (
    <>
      <Card
        bordered={false}
        className="hosts-block-card"
        size="small"
        title={
          <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
            <div
              style={{
                width: "28px",
                height: "28px",
                borderRadius: "6px",
                background: `linear-gradient(135deg, ${getBlockColor()} 0%, ${getBlockColor()}80 100%)`,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                color: "white",
                fontSize: "14px",
                fontWeight: "bold",
              }}
            >
              {getBlockInitial()}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div
                style={{
                  fontWeight: 500,
                  fontSize: "14px",
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                }}
              >
                {hostsBlock.name}
              </div>
            </div>
            <Tag
              className={`badge-sm env-${hostsBlock.environment === "生产" ? "prod" : "dev"}`}
              style={{
                borderRadius: "12px",
                padding: "0 8px",
                fontSize: "12px",
                background: hostsBlock.environment === "生产" ? "#fee2e2" : "#e0f2fe",
                color: hostsBlock.environment === "生产" ? "#dc2626" : "#0284c7",
                border: "none",
              }}
            >
              {hostsBlock.environment}
            </Tag>
          </div>
        }
        extra={
          <Space size={0}>
            <Tooltip title="编辑">
              <Button type="text" icon={<EditOutlined />} onClick={handleEdit} size="small" />
            </Tooltip>
            <Tooltip title="复制内容">
              <Button type="text" icon={<CopyOutlined />} onClick={handleCopy} size="small" />
            </Tooltip>
            <Tooltip title="删除">
              <Button type="text" danger icon={<DeleteOutlined />} onClick={handleDelete} size="small" />
            </Tooltip>
          </Space>
        }
        bodyStyle={{ padding: "12px 16px" }}
        style={{
          boxShadow: "0 1px 2px rgba(0, 0, 0, 0.03)",
          transition: "all 0.3s ease",
          border: "1px solid #f1f5f9",
        }}
      >
        {hostsBlock.description && (
          <div style={{ marginBottom: "8px", fontSize: "12px", color: "var(--gray-600)" }}>
            {hostsBlock.description}
          </div>
        )}

        <div
          className="hosts-content-compact"
          style={{
            maxHeight: isContentExpanded ? "400px" : "160px",
            fontSize: "12px",
            lineHeight: "1.4",
            fontFamily: "monospace",
            backgroundColor: "#f9fafb",
            padding: "8px",
            borderRadius: "4px",
            overflow: "auto",
          }}
        >
          {displayLines}
        </div>

        {totalLines > 8 && (
          <div style={{ textAlign: "center", marginTop: "6px" }}>
            <Button type="link" onClick={() => setIsContentExpanded(!isContentExpanded)} size="small">
              {isContentExpanded ? "收起" : `显示全部 (${totalLines} 行)`}
            </Button>
          </div>
        )}

        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            marginTop: "8px",
            color: "var(--gray-500)",
            fontSize: "12px",
          }}
        >
          <Text type="secondary" style={{ fontSize: "12px" }}>
            更新于 {new Date(hostsBlock.updatedAt).toLocaleDateString()}
          </Text>
          <Text type="secondary" style={{ fontSize: "12px" }}>
            {totalLines} 行配置
          </Text>
        </div>
      </Card>

      <Modal
        title="编辑 Hosts 配置"
        open={isEditModalVisible}
        onCancel={() => setIsEditModalVisible(false)}
        footer={null}
        width={680}
      >
        <HostsBlockForm
          initialValues={{
            name: hostsBlock.name,
            content: hostsBlock.content,
            description: hostsBlock.description,
            environment: hostsBlock.environment,
          }}
          onSubmit={handleUpdate}
          onCancel={() => setIsEditModalVisible(false)}
        />
      </Modal>
    </>
  )
}

export default HostsBlockCard
